package com.cyb.binojcodesandbox.utils;

import com.cyb.binojcodesandbox.model.ExecuteMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 进程工具类
 */
public class ProcessUtils {

    /**
     * 运行进程，获取结果
     *
     * @param runProcess
     * @return
     */
    public static ExecuteMessage runProcessAndGetMessage(Process runProcess, String opName) {
        ExecuteMessage executeMessage = new ExecuteMessage();
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            //等待编译或运行完成，返回结果
            int exitValue = runProcess.waitFor();
            executeMessage.setExitValue(exitValue);
            if (exitValue == 0) {
                System.out.println(opName + "成功");
                //分批次获取进程的正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                List<String> outPutStrList = new ArrayList<>();
                //逐行获取输出
                String compileOutputLine;
                while ((compileOutputLine = bufferedReader.readLine()) != null) {
                    outPutStrList.add(compileOutputLine);
                }
                executeMessage.setMessage(StringUtils.join(outPutStrList, "\n"));
            } else {
                System.out.println(opName + "失败 ,错误码：" + exitValue);
                //分批次获取进程的正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                List<String> outPutStrList = new ArrayList<>();
                //逐行获取输出
                String compileOutputLine;
                while ((compileOutputLine = bufferedReader.readLine()) != null) {
                    outPutStrList.add(compileOutputLine);
                }
                executeMessage.setMessage(StringUtils.join(outPutStrList, "\n"));
                //分批次获取进程的输出
                BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(runProcess.getErrorStream()));
                List<String> erroroutPutStrList = new ArrayList<>();
                //逐行获取输出
                String errorCompileOutputLine;
                while ((errorCompileOutputLine = errorBufferedReader.readLine()) != null) {
                    erroroutPutStrList.add(errorCompileOutputLine);
                }
                executeMessage.setErrorMessage(StringUtils.join(erroroutPutStrList, "\n"));
            }
            stopWatch.stop();
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return executeMessage;
    }

}
